package com.maint.m.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.maint.m.TicketItem
import com.maint.m.PageRequest
import com.maint.m.OperationTicketResponse
import com.maint.m.TicketApiService
import com.maint.m.NetworkUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class TicketListViewModel : ViewModel() {
    private val _ticketList = MutableLiveData<List<TicketItem>>()
    val ticketList: LiveData<List<TicketItem>> = _ticketList

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _errorMessage = MutableLiveData<String?>(null)
    val errorMessage: LiveData<String?> = _errorMessage

    private val _isRefreshing = MutableLiveData(false)
    val isRefreshing: LiveData<Boolean> = _isRefreshing

    private val _isLoadMore = MutableLiveData(false)
    val isLoadMore: LiveData<Boolean> = _isLoadMore

    var currentPage = 1
    private var pageSize = 10
    var totalPage = 1

    fun refreshData() {
        currentPage = 1
        loadData(currentPage)
    }

    fun loadMore() {
        if (currentPage < totalPage && !_isLoadMore.value!!) {
            loadData(currentPage + 1, true)
        }
    }

    fun loadData(pageNum: Int, isLoadMore: Boolean = false) {
        if (_isLoading.value!!) return

        _isLoading.value = true
        _errorMessage.value = null

        if (isLoadMore) {
            _isLoadMore.value = true
        } else {
            _isRefreshing.value = true
        }

        val apiService = NetworkUtils.createService(TicketApiService::class.java)
        val call = apiService.getTicketPage(PageRequest(pageNum, pageSize))

        call.enqueue(object : Callback<OperationTicketResponse> {
            override fun onResponse(
                call: Call<OperationTicketResponse>,
                response: Response<OperationTicketResponse>
            ) {
                _isLoading.value = false
                _isRefreshing.value = false
                _isLoadMore.value = false

                val body = response.body()
                if (response.isSuccessful && body != null && body.statusCode == "200") {
                    val pageData = body.result
                    val items = pageData?.records ?: emptyList()

                    totalPage = pageData?.pages ?: 1
                    currentPage = pageNum

                    if (isLoadMore) {
                        _ticketList.value = _ticketList.value.orEmpty() + items
                    } else {
                        _ticketList.value = items
                    }
                } else {
                    val errorMsg = body?.message ?: response.message() ?: "未知错误"
                    _errorMessage.value = "加载失败：$errorMsg"
                }
            }

            override fun onFailure(call: Call<OperationTicketResponse>, t: Throwable) {
                _isLoading.value = false
                _isRefreshing.value = false
                _isLoadMore.value = false
                t.printStackTrace()
                _errorMessage.value = "网络错误：${t.message}"
            }
        })
    }

    fun createStructuredMessage(): String {
        // 创建 JSON 格式的消息
        val messageMap = mapOf(
            "business" to 1
        )
        return Gson().toJson(messageMap)
    }
}

// 数据类已在TicketApiService中定义